package com.micro.ai.gateway.filter;

import com.micro.ai.commons.constant.ErrorCodeEnum;
import com.micro.ai.commons.domain.ApiResponse;
import com.micro.ai.commons.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 异常处理过滤器
 * 统一处理过滤器链中的异常
 * 
 * @author micro-ai
 * @since 0.0.1
 */
@Slf4j
@Component
public class ExceptionHandlerFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return chain.filter(exchange)
                .onErrorResume(throwable -> {
                    log.error("网关过滤器异常: {}", throwable.getMessage(), throwable);
                    return handleException(exchange, throwable);
                });
    }

    @Override
    public int getOrder() {
        return 1000; // 最低优先级，最后执行
    }

    /**
     * 处理异常
     */
    private Mono<Void> handleException(ServerWebExchange exchange, Throwable throwable) {
        ServerHttpResponse response = exchange.getResponse();
        
        HttpStatus status = HttpStatus.INTERNAL_SERVER_ERROR;
        String message = "系统内部错误";
        String code = ErrorCodeEnum.B0001.getCode();
        
        if (throwable instanceof ResponseStatusException) {
            ResponseStatusException ex = (ResponseStatusException) throwable;
            status = HttpStatus.valueOf(ex.getStatusCode().value());
            
            switch (status) {
                case UNAUTHORIZED:
                    code = ErrorCodeEnum.A0006.getCode();
                    message = "未授权访问";
                    break;
                case FORBIDDEN:
                    code = ErrorCodeEnum.A0007.getCode();
                    message = "权限不足";
                    break;
                case NOT_FOUND:
                    code = ErrorCodeEnum.C0002.getCode();
                    message = "服务不存在";
                    break;
                case SERVICE_UNAVAILABLE:
                    code = ErrorCodeEnum.B0002.getCode();
                    message = "服务不可用";
                    break;
                case GATEWAY_TIMEOUT:
                    code = ErrorCodeEnum.B0002.getCode();
                    message = "请求超时";
                    break;
                default:
                    code = ErrorCodeEnum.B0001.getCode();
                    message = "系统异常";
                    break;
            }
        } else if (throwable instanceof java.util.concurrent.TimeoutException) {
            status = HttpStatus.GATEWAY_TIMEOUT;
            code = ErrorCodeEnum.B0002.getCode();
            message = "请求超时";
        } else if (throwable instanceof java.net.ConnectException) {
            status = HttpStatus.SERVICE_UNAVAILABLE;
            code = ErrorCodeEnum.B0002.getCode();
            message = "服务不可用";
        }
        
        response.setStatusCode(status);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        
        ApiResponse<Void> apiResponse = ApiResponse.error(code, message);
        String body = JsonUtils.toJson(apiResponse);
        
        DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
